#include<vector>
#include<queue>
using namespace std;
class Solution
{
public:
    int maxCandies(vector<int> &status, vector<int> &candies, vector<vector<int>> &keys, vector<vector<int>> &containedBoxes, vector<int> &initialBoxes)
    {
        int n = status.size();
        vector<int> has_box(n, 0);
        vector<int> can_open_box(n, -1);
        vector<int> used(n, 0);
        int ans = 0;
        for (int i = 0; i < n; i++)
        {
            if (status[i] == 1)
            {
                can_open_box[i] = 1;
            }
        }

        // 拥有并且可以打开才能入获得糖果
        queue<int> q;
        for (int &i : initialBoxes) // i:已经得到的盒子
        {
            has_box[i] = 1;
            if (can_open_box[i] == 1 && has_box[i] == 1)
            {
                q.push(i);
                used[i] = 1;
                ans += candies[i];
            }
        }

        while (!q.empty())
        {
            int k = q.front(); // 当前盒子编号
            q.pop();

            for (int &key : keys[k])
            {
                can_open_box[key] = 1;
                // 枚举钥匙
                if (has_box[key] == 1 && used[key] == 0)
                {
                    q.push(key);
                    ans += candies[key];
                    used[key] = 1;
                }
            }

            for (auto &box : containedBoxes[k])
            {
                has_box[box] = 1;
                // 添加包含的盒子
                if (used[box] == 0 && can_open_box[box] == 1)
                {
                    q.push(box);
                    ans += candies[box];
                    used[box] = 1;
                }
            }
        }
        return ans;
    }
};